﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http.Filters;
using System.Net.Http;

namespace HttpController.Filters
{
    public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public string ErrorMsg { get; set; }

        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnException(actionExecutedContext);

            if (actionExecutedContext.Response == null)
            {
                actionExecutedContext.Response = new System.Net.Http.HttpResponseMessage();
            }

            if (actionExecutedContext.Exception != null)
            {
                // we can log the detail exception here
            }

            string json = @"{""code"":1,""msg"":"""
                + ErrorMsg + @""",""time"":"""
                + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + @"""}";
            actionExecutedContext.Response.StatusCode = System.Net.HttpStatusCode.OK;
            actionExecutedContext.Response.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
        }
    }
}